export default class EventCenter {
    private eventTargetList;
    private dispatchList;

    //注册事件
    public RegisterEvent(uuid, key, callback) {
        if (!uuid) {
            return;
        }
        if (!key) {
            return;
        }
        if (!callback) {
            return;
        }
        //初始化
        if (!this.eventTargetList) {
            this.eventTargetList = {};
        }
        if (!this.eventTargetList[uuid]) {
            this.eventTargetList[uuid] = {};
        }
        if (!this.eventTargetList[uuid][key]) {
            this.eventTargetList[uuid][key] = [];
        }

        this.eventTargetList[uuid][key].push(callback);
    }

    public DispatchEvent(key, data = null) {
        if (!key) {
            return;
        }
        if (this.eventTargetList) {

            for (var target in this.eventTargetList) {
                if (this.eventTargetList[target]) {
                    var eventList = this.eventTargetList[target]
                    if (eventList[key]) {
                        var callbackArr = eventList[key];
                        if (callbackArr) {
                            for (var i = 0; i < callbackArr.length; i++) {
                                callbackArr[i](data);
                            }
                        }
                    }
                }
            }
        }
    }

    public DispatchEventSync(key) {
        if (!this.dispatchList) {
            this.dispatchList = [];
        }

        if (!key) {
            return;
        }

        this.dispatchList.push(key);
    }

    public FrameOnMove(dt) {
        if (this.dispatchList && this.dispatchList.length > 0) {
            var len = this.dispatchList.length;
            for (var i = 0; i < len; i++) {
                var key = this.dispatchList[i];
                this.DispatchEvent(key);
            }
            this.dispatchList.length = 0;
        }
    }

    public RemoveEvent(uuid) {
        if (!uuid) {
            return;
        }
        if (this.eventTargetList && this.eventTargetList[uuid]) {
            delete this.eventTargetList[uuid];
        }
    }

    public ClearAll() {
        if (this.eventTargetList) {
            this.eventTargetList = null;
        }
        if (this.dispatchList) {
            this.dispatchList.length = 0;
            this.dispatchList = null;
        }
    }
}